#pragma once
#include<iostream>

#include<assert.h>
using namespace std;


namespace bit
{
	class string
	{
	public:
		typedef char* iterator;
		typedef const char* const_iterator;
		iterator begin()
		{
			return _str;
		}
		iterator end()
		{
			return _str + _size;
		}
		const_iterator begin()const 
		{
			return _str;
		}
		const_iterator end()const
		{
			return _str+_size;
		}
		//构造函数，非自定义类型，不推崇初始化列表,全省默认传"\0"
		string(const char* str = "")
		{
			_size = strlen(str);
			_capacity = _size;
			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}

		string(const string& s)
			:_capacity(s._capacity)
			, _size(s._size)
			,_str(new char[_capacity+1])
			
		{
			strcpy(_str, s._str);
		}

		//现代写法
		void swap(string& tmp)
		{
			::swap(_str, tmp._str);
			::swap(_capacity, tmp._capacity);
			::swap(_size, tmp._size);
		}
		string(const string& s)
			:_str(nullptr)
			,_capacity(0)
			,_size(0)
		{
			string tmp(s._str);
			//swap(_str, tmp._str);
			//swap(_capacity, tmp._capacity);
			//swap(_size, tmp._size);
			swap(tmp);
		}


		string& operator=(const string& s)
		{
			if (this != &s)
			{
				//string tmp(s._str);
				string tmp(s);
				swap(tmp); 
			}
		}

		~string()
		{
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;
		}
		const char* c_str()const
		{
			return _str;
		}

		size_t size()const
		{
			return _size;
		}
		const char& operator[](size_t pos)const
		{
			assert(pos < _size);
			return _str[pos];
		}
		char& operator[](size_t pos)
		{
			assert(pos < _size);
			return _str[pos];
		}
		void push_back(char ch);
		void append(const char* str);
		string& operator+=(char ch);
		string& operator+=(const char* str);
	private:
		size_t _size;
		size_t _capacity;
		char* _str;
	};
	void test_string1()
	{
		//std::string s1("hello world");
		//std::string s2;
		string s1("hello world");
		string s2;

		cout << s1.c_str() << endl;
		cout << s2.c_str() << endl;

		for (size_t i = 0; i < s1.size(); ++i)
		{
			cout << s1[i] << " ";
		}
		cout << endl;

		for (size_t i = 0; i < s1.size(); ++i)
		{
			s1[i]++;
		}

		for (size_t i = 0; i < s1.size(); ++i)
		{
			cout << s1[i] << " ";
		}
		cout << endl;
	}
}
